$(function () {
    layui.use(['table', 'laydate', 'form'], function () {
        table = layui.table
        var laydate = layui.laydate, $ = layui.$;
        form = layui.form;
        laydate.render({
            elem: '#ID-laydate-range',
            range: ['#createTime', '#endTime'],
            rangeLinked: true,
            type: 'datetime',
            shortcuts: [
                {
                    text: "上个月",
                    value: function () {
                        var date = new Date();
                        var year = date.getFullYear();
                        var month = date.getMonth();
                        return [
                            new Date(year, month - 1, 1),
                            new Date(year, month, 0)
                        ];
                    }
                }, {
                    text: "这个月",
                    value: function () {
                        var date = new Date();
                        var year = date.getFullYear();
                        var month = date.getMonth();
                        return [
                            new Date(year, month, 1),
                            new Date(year, month + 1, 0)
                        ];
                    }
                },
                {
                    text: "下个月",
                    value: function () {
                        var date = new Date();
                        var year = date.getFullYear();
                        var month = date.getMonth();
                        return [
                            new Date(year, month + 1, 1),
                            new Date(year, month + 2, 0)
                        ];
                    }
                }
            ],
            done: function (value, date, endDate) {
                let mydataList = value.split(' - ')
                $('#createTime').val(mydataList[0])
                $('#endTime').val(mydataList[1])
                setMyWhere()
            }
        });
        // 创建渲染实例
        table.render({
            elem: '#exampleTable'
            , id: 'exampleTable'
            , url: myUrl
            ,method:'get'
            ,contentType: 'application/x-www-form-urlencoded'
            // ,contentType: 'application/json'
            , cellMinWidth: 80
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                , curr: pages //设定初始在第 5 页
                , groups: 5 //只显示 1 个连续页码
                , limit: 15
                , limits : [15,30,50,100,200]
            }
            , request: {
                pageName: 'current' //页码的参数名称，默认：page
                , limitName: 'size'
            }
            , where: myWhere
            , defaultToolbar: false
            , loading: false
            , cols:myCols
            , response: {
                statusCode: 0 //重新规定成功的状态码为 200，table 组件默认为 0
            }
            , parseData: function (res) {
                setSZMX()
                if (res.code != 0) {
                    return false;
                }
                if(Number(res.data.total)>0&&res.data.records.length==0){
                    pages--;
                    if(pages>0) {
                        table.reload('exampleTable', {
                            page: {curr: pages},
                            where: myWhere
                        })
                    }
                }
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            }
            , jump: function (obj, first) {
                //首次不执行
                if (!first) {
                    pages = obj.curr
                }
            }
            , error: function (res, msg) {
                console.log(res, msg)
            }
            , done: function (res) {
                layer.close()
                hindLoading()
            }
        });

        var $ = layui.$, active = {
            reload: function () {
                setMyWhere()
                //执行重载
                table.reload('exampleTable', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    , where: myWhere
                });
            }
        };

        /**
         * 搜索事件
         */
        $('.demoTable .layui-btn').on('click', function () {
            var type = $(this).data('type');
            setMyWhere()
            active[type] ? active[type].call(this) : '';
        });

    });


});
let table = null;
let myUrl = '/jzweb/jazOrderDetail/selOrderDetailList'
let myWhere = {},form =null;

const setSZMX=()=>{
    $('#span1').html('-')
    $('#span2').html('-')
    $('#span3').html('-')
    $.ajax({
        url:`/jzweb/jazOrderDetail/selOrderDetailMoney?createTime=${myWhere.createTime}&endTime=${myWhere.endTime}&type=${myWhere.type}`,
        type:'get',
        success:function (r) {
            if (r.code == 0){
                $('#span1').html(r.data.netIncome)
                $('#span2').html(r.data.totalIncome)
                $('#span3').html(r.data.totalExpenditure)
            }else{
                $('#span1').html('-')
                $('#span2').html('-')
                $('#span3').html('-')
            }
        },error:function(){

            $('#span1').html('-')
            $('#span2').html('-')
            $('#span3').html('-')
        }
    })
}
const setMyWhere = () => {
    myWhere = {
        createTime: $("#createTime").val(),
        endTime: $("#endTime").val(),
        type: $("#type").val()==''?-1:parseInt($("#type").val()),
    }
}
setMyWhere()
let myCols = [[
        {
            field: 'orderCode',
            title: '订单号',
            align: 'center',
        templet: function (d) {
    return   `<span>${d.orderCode}</span>`

}
        },
        {
            field: 'prodName',
            align: 'center',
            title: '商品名称'
        },
        {
            field: 'userName',
            align: 'center',
            title: '用户名称'
        },
        {
            field: 'phone',
            align: 'center',
            title: '电话号码'
        },
    {
        field: 'money',
        align: 'center',
        title: '金额',
        templet: function (d) {
            return   `<span>${d.money}</span>`

        }
    },
        {
            field: 'type',
            align: 'center',
            title: '交易类型',
            templet: function (d) {
                return d.type=="0"?
                '<span class="label label-primary">收入</span>':
                    d.type=="1"?
                '<span class="label label-warning">支出</span>':'<span class="label label-warning">-</span>'

            }
        },
        {
            field: 'tradeDesc',
            align: 'center',
            title: '交易描述'
        },
        {
            field: 'tradeTime',
            align: 'center',
            title: '交易日期',
            templet: function (d) {
                return   `<span>${d.tradeTime}</span>`

            }
        },
    ]]

/**
 * 重置
 */
const dataReset = () => {
    $("#createTime").val('')
    $("#endTime").val('')
    $("#type").val('')
    form.render('select');
    setMyWhere()
    table.reload('exampleTable', {
        page: {
            curr: 1 //重新从第 1 页开始
        }
        , where: myWhere
    });
}
let pages = 1;

/**
 * 所有的重置表格
 */
function load(){
    layui.use(['table'], ()=>{
        layui.table.reload('exampleTable',{
            where: myWhere
        })
    })
}

const daochu=()=>{
    var rows = table.checkStatus('exampleTable').data
    layer.confirm(rows.length>0?'确认导出选中的'+rows.length+'条数据吗？':"确认要导出表格数据吗？", {
        btn : [ '确定', '取消' ]
        // 按钮
    }, function(index, layero) {
        console.log('导出')
        //参数
        setMyWhere()
        // let str='?'
        // Object.keys(myWhere).forEach(key=>{
        //     if(myWhere[key]!=null){
        //         str+=`${key}=${myWhere[key]}&`
        //     }
        // })
        // var ids = new Array();
        // if(rows.length>0){
        //     $.each(rows, function(i, row) {
        //         ids[i] = row['id'];
        //     });
        // }
        // str+=`ids=${ids}`
        let objkey=Object.keys(myWhere)
        let str=''
        objkey.map(item=>{
            str+=item+'='+myWhere[item]+'&'
        })
        str=str.substring(0,str.length-1)
        // window.location.href = `/jzweb/jazOrderDetail/downloadImportTemplate?${str}`
        myDownFiles(`/jzweb/jazOrderDetail/downloadImportTemplate?${str}`)
        layer.close(index);
    }, function() {
    })
}